/*
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the FxStruts MailReader Application.
 *
 * The Initial Developer of the Original Code is
 * Anirudh Sasikumar (http://anirudhs.chaosnet.org/).
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
*/

package com.adobe.mailreader.command
{
    import com.adobe.cairngorm.commands.ICommand;
    import com.adobe.cairngorm.control.CairngormEvent;
    import com.adobe.cairngorm.control.CairngormEventDispatcher;
    import com.adobe.mailreader.business.AccountCreateEditDelegate;
    import com.adobe.mailreader.events.AccountCreateEditEvent;
    import com.adobe.mailreader.events.SubscriptionEvent;
    import com.adobe.mailreader.model.MailModelLocator;
    import com.adobe.mailreader.vo.UserVO;
    
    import flash.utils.ByteArray;
    
    import mx.controls.Alert;
    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;
    
    /* Account creation and editing  */
    public class AccountCreateEditCommand implements ICommand, IResponder
    {
        private var actionState:Boolean = false;
    	private var voData:UserVO;
    	private var evtType:String;
        private var model : MailModelLocator;

        public function AccountCreateEditCommand()
        {
            model = MailModelLocator.getInstance();
            
        }
        
        public function execute( event:CairngormEvent ):void
        {
            var userEvt:AccountCreateEditEvent = event as AccountCreateEditEvent;
            var subDelegate:AccountCreateEditDelegate = new AccountCreateEditDelegate(this);

            /* Save details, then get the token for the operation and
             * then perform the actual action */
            if ( userEvt.userData != null )
            {
                evtType = userEvt.type;
                voData = userEvt.userData;

                subDelegate.confirmAccount();

                
            }
            else
            {
                Alert.show("Null evt passed to account create / edit command");
            } 	              
        }
        
        public function result( event : Object ) : void
        {				
            trace("Got result " + event.result);
            model.transactionToken = "";

            /* check if this is the token result or not */
            if ( !actionState )
            {
                if ( event.result is Object && event.result.hasOwnProperty("result") && 
                     event.result.hasOwnProperty("org.apache.struts.taglib.html.TOKEN")  )
                {
                    /* save token and perform the actual operation */
                    model.transactionToken = event.result["org.apache.struts.taglib.html.TOKEN"];
                    performAction(new AccountCreateEditDelegate(this), voData);
                    actionState = true;
                    return;
                }
            }

            if ( event.result is Object && event.result.hasOwnProperty("errors") )
            {
                model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_FAILED, event.result.errors);
            }
            else if ( event.result is UserVO )
            {
                model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_SUCCESS);
            }
            else if ( event.result == "true" )
            {
                model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_SUCCESS);
            }
            else
                model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_FAILED, "Unexpected error occurred while editing data");	
        }
        
        public function fault( event : Object ) : void
        {
            trace("Got fault" + event);
            var str:String = "";
            var faultEvent:FaultEvent = event as FaultEvent;
            if ( faultEvent )
            {
                if ( faultEvent.fault.faultCode == "Client.CouldNotDecode" )
                {
                    str = (faultEvent.message.body as ByteArray).toString();
                    model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_FAILED, str);
                    /* if we got html instead of AMF, this would be useful */
                    Alert.show("Str err: " + str);
                    return;
                }
            }
            model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_FAILED, event.fault.faultString);
        }

        private function performAction(subDelegate:AccountCreateEditDelegate, vo:UserVO):void
        {
            if ( evtType == AccountCreateEditEvent.EVENT_AccountCreateEdit_EDIT )
            {      	            	 
                subDelegate.editAccount(vo.username,
                                        vo.password,
                                        vo.password2,
                                        vo.fullName,
                                        vo.fromAddress,
                                        vo.replyToAddress,
                                        model.transactionToken);
            }
            else if ( evtType == AccountCreateEditEvent.EVENT_AccountCreateEdit_CREATE )
            {
                subDelegate.createAccount(vo.username,
                                          vo.password,
                                          vo.password2,
                                          vo.fullName,
                                          vo.fromAddress,
                                          vo.replyToAddress,
                                          model.transactionToken);
            }

        }
        
    }
}